package com.witframework.util;

import java.io.Serializable;
import java.net.InetAddress;
import java.util.Calendar;



public class TimestampBasedUIDGenerator {

	private static String hexInetAddress;
	private static long TIMENOW;
	private static long sequence=0;
	private static String setup;
	static{
		InetAddress inet = null;
		try {
			inet = InetAddress.getLocalHost();
		} catch (java.net.UnknownHostException uhe) {
		}
		hexInetAddress = inetToString(inet);
		Calendar c=Calendar.getInstance();
		c.setTimeInMillis(System.currentTimeMillis());
		setup=String.valueOf(c.get(Calendar.YEAR));
		setup=setup.substring(2)+(c.get(Calendar.MONTH)+1)+c.get(Calendar.DAY_OF_MONTH);		
		
	}
	public Serializable generate(Object entity){
		return generate();
	}	
	public Serializable generate(){
		long timeNow = System.currentTimeMillis();
		return (hexInetAddress +setup+timeNow+getSequence(timeNow));
	}
	private synchronized long getSequence(long time){
		if(time!=TIMENOW){
			sequence=0;
			TIMENOW=time;
		}
		return sequence++;
	}

	private static String inetToString(InetAddress inet) {
		StringBuffer sb = new StringBuffer();
		byte[] b = inet.getAddress();
		int i;
		int v;
		for (i = 0; i < b.length; i++) {
			// Convert to an unsigned value
			v = b[i] < 0 ? (Byte.MAX_VALUE + 1) * 2 + b[i] : b[i];
			if (v <= 0xF)
				sb.append("0");
			sb.append(Integer.toHexString(v));
		}
		return (new String(sb));
	}
	public static void main(String[] s){
		for(int i=0;i<100;i++){
			System.out.println(new TimestampBasedUIDGenerator().generate());
		}
	}
}
